// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const db = uniCloud.database();
const dbCarSchedules = db.collection('car_schedules');
const dbMealSchedules = db.collection('meal_schedules')


module.exports = {
	_before: function() { // 通用预处理器

	},

	async getCarSchedules(event) {
		try {
			let query = {};

			// 状态筛选
			if (event.status !== undefined) {
				query.status = event.status;
			}
			

			// 模糊搜索用户名
			if (event.keyword) {
				const keyword = event.keyword.trim();
				query.username = new RegExp(keyword, 'i'); // 只匹配 username
			}

			// 分页
			const page = event.page || 1;
			const pageSize = event.pageSize || 10;

			const res = await dbCarSchedules
				.where(query)
				.orderBy('create_date', 'desc')
				.skip((page - 1) * pageSize)
				.limit(pageSize)
				.get();

			const totalQuery = {
				...query
			}; // 复制查询条件
			const total = await dbCarSchedules.where(totalQuery).count();

			return {
				code: 0,
				message: '查询成功',
				data: res.data,
				total: total.total
			};
		} catch (error) {
			console.error('车辆日程查询异常:', error);
			return {
				code: 500,
				message: '服务器内部错误',
				error_detail: error.message
			};
		}
	},
	
	async getCarSchedulesByMobile(event) {
		try {
			let query = {};
	
			// 状态筛选
			if (event.status !== undefined) {
				query.status = event.status;
			}
			
			if (event.mobile !== undefined) {
				query.mobile = event.mobile;
			}
			
	
			// 模糊搜索目的地
			if (event.keyword) {
				const keyword = event.keyword.trim();
				query.destination = new RegExp(keyword, 'i'); // 只匹配 destination
			}
	
			// 分页
			const page = event.page || 1;
			const pageSize = event.pageSize || 10;
			console.log(query,'查询条件')
			const res = await dbCarSchedules
				.where(query)
				.orderBy('create_date', 'desc')
				.skip((page - 1) * pageSize)
				.limit(pageSize)
				.get();
	
			const totalQuery = {
				...query
			}; // 复制查询条件
			const total = await dbCarSchedules.where(totalQuery).count();
	
			return {
				code: 0,
				message: '查询成功',
				data: res.data,
				total: total.total
			};
		} catch (error) {
			console.error('车辆日程查询异常:', error);
			return {
				code: 500,
				message: '服务器内部错误',
				error_detail: error.message
			};
		}
	},
	
	async getCarSchedulesByDriverMobile(event) {
		try {
			let query = {};
	
			// 状态筛选
			if (event.status !== undefined) {
				query.status = event.status;
			}
			
			if (event.driver_mobile !== undefined) {
				query.driver_mobile = event.driver_mobile;
			}
			
	
			// 模糊搜索目的地
			if (event.keyword) {
				const keyword = event.keyword.trim();
				query.destination = new RegExp(keyword, 'i'); // 只匹配 destination
			}
	
			// 分页
			const page = event.page || 1;
			const pageSize = event.pageSize || 10;
			console.log(query,'查询条件')
			const res = await dbCarSchedules
				.where(query)
				.orderBy('create_date', 'desc')
				.skip((page - 1) * pageSize)
				.limit(pageSize)
				.get();
	
			const totalQuery = {
				...query
			}; // 复制查询条件
			const total = await dbCarSchedules.where(totalQuery).count();
	
			return {
				code: 0,
				message: '查询成功',
				data: res.data,
				total: total.total
			};
		} catch (error) {
			console.error('车辆日程查询异常:', error);
			return {
				code: 500,
				message: '服务器内部错误',
				error_detail: error.message
			};
		}
	},

	async getCarSchedulesById(event, content) {
		if (event._id) {
			let res = await dbCarSchedules.where(event).get()
			// console.log(res.data, "data")
			return res.data[0]
		} else {
			let res = await dbCarSchedules.get()
			// console.log("error")
			return res.data
		}


	},

	async getDriverSchedulesByMobile(event, content) {
		if (event.mobile) {
			let res = await dbCarSchedules.where({
				status: 1,
				driver_mobile: event.mobile
			}).get()
			return res
		} else {

		}

	},
	//
	async updateCarSchedules(event) {
		try {
			// 参数校验
			if (!event?._id) {
				return {
					code: -2,
					message: '缺少车辆预约ID参数'
				};
			}
			if (!event?.data || typeof event.data !== 'object' || Object.keys(event.data).length === 0) {
				return {
					code: -3,
					message: '更新数据不能为空且必须为对象格式'
				};
			}

			// 执行更新操作
			const updateResult = await dbCarSchedules
				.doc(event._id)
				.update(event.data);

			// 处理更新结果
			if (updateResult.updated === 0) { // 根据实际数据库驱动调整字段
				return {
					code: 1,
					message: '数据未发生变更',
					updatedId: event._id
				};
			}

			return {
				code: 0,
				message: '数据更新成功',
				updatedId: event._id,
				affected: updateResult.updated, // 实际更新的文档数量
				timestamp: new Date().toISOString() // 添加操作时间戳
			};
		} catch (error) {
			console.error('车辆排班更新异常:', error.message);

			// 错误分类处理
			const errorInfo = {
				code: -1,
				message: '更新操作失败',
				detail: process.env.NODE_ENV === 'development' ? {
					error: error.message,
					stack: error.stack
				} : undefined
			};

			// 特定错误类型识别
			if (error.message.includes('DocumentNotFound')) {
				errorInfo.code = -4;
				errorInfo.message = '指定预约记录不存在';
			} else if (error.message.includes('InvalidData')) {
				errorInfo.code = -5;
				errorInfo.message = '提交数据格式非法';
			}

			return errorInfo;
		}
	},

	// async getCarSchedules(event, content) {
	// 	let res = await dbCarSchedules.get()
	// 	return res
	// },
	//新增用车申请
	async addCarSchedules(event, content) {
		try {
			const res = await dbCarSchedules.add(event);
			return {
				code: 0,
				message: '添加成功',
				data: res
			};
		} catch (e) {
			console.error('添加失败:', e);
			return {
				code: e.code || -1,
				message: e.message || '添加失败',
				error: process.env.NODE_ENV === 'development' ? e : undefined
			};
		}
	},


	async addMealSchedules(event, content) {
		try {
			const res = await dbMealSchedules.add(event);
			return {
				code: 0,
				message: '添加成功',
				data: res
			};
		} catch (e) {
			console.error('添加失败:', e);
			return {
				code: e.code || -1,
				message: e.message || '添加失败',
				error: process.env.NODE_ENV === 'development' ? e : undefined
			};
		}
	},

	async getMealSchedulesById(event, content) {
		if (event._id) {
			try {
				let res = await dbMealSchedules.where(event).get()
				return {
					code: 0,
					message: '查询成功',
					data: res.data[0]
				}
			} catch (e) {
				return {
					code: -1,
					message: '查询失败'
				}
			}

		} else {
			return {
				code: -1,
				message: 'id缺失'
			}
		}
	},

	async getMealSchedules(event, content) {
		try {
			let query = {};
		
			// 状态筛选
			if (event.status !== undefined) {
				query.status = event.status;
			}
		
			// 模糊搜索用户名
			if (event.keyword) {
				const keyword = event.keyword.trim();
				query.username = new RegExp(keyword, 'i'); // 只匹配 username
			}
		
			// 分页
			const page = event.page || 1;
			const pageSize = event.pageSize || 10;
		
			const res = await dbMealSchedules
				.where(query)
				.orderBy('create_date', 'desc')
				.skip((page - 1) * pageSize)
				.limit(pageSize)
				.get();
		
			const totalQuery = {
				...query
			}; // 复制查询条件
			const total = await dbMealSchedules.where(totalQuery).count();
		
			return {
				code: 0,
				message: '查询成功',
				data: res.data,
				total: total.total
			};
		} catch (error) {
			console.error('车辆日程查询异常:', error);
			return {
				code: 500,
				message: '服务器内部错误',
				error_detail: error.message
			};
		}
	},
	
	async getMealSchedulesByMoile(event, content) {
		try {
			let query = {};
		
			// 状态筛选
			if (event.status !== undefined) {
				query.status = event.status;
			}
			
			if (event.mobile !== undefined) {
				query.mobile = event.mobile;
			}
		
			// 模糊搜索用户名
			if (event.keyword) {
				const keyword = event.keyword.trim();
				query.dinner_time = new RegExp(keyword, 'i'); // 只匹配 dinner_time
			}
			console.log(query,'查询条件')
			// 分页
			const page = event.page || 1;
			const pageSize = event.pageSize || 10;
		
			const res = await dbMealSchedules
				.where(query)
				.orderBy('create_date', 'desc')
				.skip((page - 1) * pageSize)
				.limit(pageSize)
				.get();
		
			const totalQuery = {
				...query
			}; // 复制查询条件
			const total = await dbMealSchedules.where(totalQuery).count();
		
			return {
				code: 0,
				message: '查询成功',
				data: res.data,
				total: total.total
			};
		} catch (error) {
			console.error('订餐记录查询异常:', error);
			return {
				code: 500,
				message: '服务器内部错误',
				error_detail: error.message
			};
		}
	},
	
	async updateMealSchedules(event, content) {
		try {
			const res = await dbMealSchedules.doc(event._id).update(event.data)
			return {
				code: 0,
				message: '更新成功'
			}
		} catch (e) {
			return {
				code: -1,
				message: '更新失败'
			}
		}
	}


	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	/* 
	method1(param1) {
		// 参数校验，如无参数则不需要
		if (!param1) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		// 业务逻辑
		
		// 返回结果
		return {
			param1 //请根据实际需要返回值
		}
	}
	*/

	//用车审批
	// async updateCarSchedules(event, content) {
	// 	let res = await dbCarSchedules.doc(event._id).update(event.data)
	// 	return res
	// }
}